﻿using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Text;

namespace Neo4jRestSharp.Neo4jRestServices
{
	internal class RequestMaker
	{
		public Tuple<HttpStatusCode, Uri, string> MakeRequest(HttpWebRequest request)
		{
		    HttpWebResponse response = null;
		    Stream responseStream = null;

            try
            {
                try
                {
                    response = (HttpWebResponse)request.GetResponse();
                }
                catch (WebException we)
                {
                    response = (HttpWebResponse)we.Response;
                    return Tuple<HttpStatusCode, Uri, string>.Create<HttpStatusCode, Uri, string>(response.StatusCode, null, we.Message);
                }

                HttpStatusCode statusCode = response.StatusCode;

                Uri location;
                try
                {                    
                    location = new Uri(response.Headers["Location"]);
                }
                catch (Exception)
                {
                    location = null;
                }

                responseStream = response.GetResponseStream();

                var readStream = new StreamReader(responseStream, Encoding.UTF8);
                var buffer = new Char[256];

                var stringBuilder = new StringBuilder();
                int count = readStream.Read(buffer, 0, 256);

                while (count > 0)
                {
                    var str = new String(buffer, 0, count);

                    stringBuilder.Append(str);

                    count = readStream.Read(buffer, 0, 256);
                }

                var responseData = stringBuilder.ToString();

                return Tuple<HttpStatusCode, Uri, string>.Create(statusCode, location, responseData);
            }
            finally
            {
                if (response != null)
                    response.Close();
                if (responseStream != null)
                    responseStream.Dispose();
            }
		}
	}
}
